<?php
/*
 * Created on 29.01.2006
 * 
 * config:
 * target       target to redirect to (optional)
 * add-slash    should a slash be added to url (default is true)
 */

m2import('phpinchains/Filter.php');

class RedirectFilter extends phpinchains_Filter
{
    
    var $config;
    var $slash;

    function doFilter (& $env, & $chain)
    {
        if (isset($this->config['target']) && (preg_match('#^(http://|//)#', $this->config['target'])
            || (isset($this->config['condition']) && $this->config['condition'])))
        {
            if (isset($this->config['condition']))
            {
                header("Location: ".$env->getServer('SCRIPT_NAME').$this->config['target']);
            }
            else
            {
                if ($this->config['target']{0} == '/')
                {
                    $this->config['target'] = substr($this->config['target'], 1);
                }
                header("Location: ".$this->config['target']);
            }
            return;
        }
        if ($chain->getRunFilter() == 1 && !isset($this->config['condition']))
        {
            if ($this->config['target'] && $env->getServer('PATH_INFO') != $this->config['target'].'/')
            {
                header("Location: ".$env->getServer('SCRIPT_NAME').$this->config['target'].$this->slash);
                return;  
            }
            else
            {
                $pi = $env->getServer('PATH_INFO');
                if ($pi{strlen($pi)-1} != '/')
                    header("Location: ".$env->getServer('SCRIPT_NAME').$pi.'/');
                else
                {
                    $chain->decRunFilter();
                    $chain->doFilter($env);
                }
                return;
            }
        }
        $chain->decRunFilter();
        $chain->doFilter($env);
    }
    
    function init (& $config)
    {
        $this->config = & $config;
        if (empty($config['add-slash']) || $config['add-slash'] == 'true')
        {
            $this->slash = '/';
        }
        elseif ($config['add-slash'] == 'false')
        {
            $this->slash = '';
        }
        else
        {
            print "<b>RedirectFilter:</b> add-slash value has to be true or false or empty<br/>";
            exit;
        }
    }

}
?>